package com.cskaoyan.market.controller;

import com.cskaoyan.market.db.domain.MarketStorage;
import com.cskaoyan.market.service.WxStorageService;
import com.cskaoyan.market.util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.UUID;

/**
 * @Author: 付诚
 * @Date: 2024/5/22 9:49
 * @Description:
 */
@RestController
@RequestMapping("/wx/storage")
public class WxStorageController {
    @Autowired
    private WxStorageService wxStorageService;

    @PostMapping("/upload")
    public Object upload(MultipartFile file) {

        try {
            file.getInputStream();
        } catch (IOException e) {
            return ResponseUtil.fail(401, "文件读取失败");
        }
        String originalFilename = file.getOriginalFilename();
        String imagePath = UUID.randomUUID() + "_" + originalFilename;
        File file1 = new File("D://wangdao//image", imagePath);
        try {
            file.transferTo(file1);
        } catch (IOException e) {
            return ResponseUtil.fail(401, "文件保存失败");
        }
        MarketStorage data = new MarketStorage();

        data.setName(file.getOriginalFilename());
        data.setAddTime(LocalDateTime.now());
        data.setKey(imagePath);
        data.setSize((int)file.getSize());
        data.setType(file.getContentType());
        data.setUrl("http://localhost:8083/wx/storage/fetch/" + imagePath);
        data.setUpdateTime(LocalDateTime.now());

        wxStorageService.upload(data);

        return ResponseUtil.ok(data);
    }

}
